import http from './http'

// 基础API服务类
class BaseApiService {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
  }

  // 通用CRUD方法
  async getList(params = {}) {
    return http.get(this.baseUrl, { params })
  }

  async getById(id) {
    return http.get(`${this.baseUrl}/${id}`)
  }

  async create(data) {
    return http.post(this.baseUrl, data)
  }

  async update(id, data) {
    return http.put(`${this.baseUrl}/${id}`, data)
  }

  async delete(id) {
    return http.delete(`${this.baseUrl}/${id}`)
  }

  async search(keyword, params = {}) {
    return http.get(`${this.baseUrl}/search`, { 
      params: { keyword, ...params } 
    })
  }
}

// 认证相关API
export const authApi = {
  login: (data) => http.post('/Auth/login', data),
  register: (data) => http.post('/Auth/register', data),
  logout: (data) => http.post('/Auth/logout', data),
  refresh: () => http.post('/Auth/refresh'),
  getInfo: () => http.get('/User/info'),
  forgotPassword: (data) => http.post('/Auth/forgot-password', data),
  resetPassword: (data) => http.post('/Auth/reset-password', data)
}

// 用户管理API
export class UserApiService extends BaseApiService {
  constructor() {
    super('/User')
  }

  // 用户特定方法
  async changePassword(data) {
    return http.post('/User/change-password', data)
  }

  async updateProfile(data) {
    return http.put('/User/profile', data)
  }

  async uploadAvatar(formData) {
    return http.post('/User/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }

  async getUserRoles(userId) {
    return http.get(`/User/${userId}/roles`)
  }

  async assignRoles(userId, roleIds) {
    return http.post(`/User/${userId}/roles`, { roleIds })
  }

  // 兼容现有API的方法名
  async getUsers(params = { page: 1, pageSize: 10 }) {
    return this.getList(params)
  }

  async searchUsers(keyword) {
    return this.search(keyword)
  }

  async addUser(data) {
    return this.create(data)
  }

  async updateUser(id, data) {
    return this.update(id, data)
  }

  async deleteUser(id) {
    return this.delete(id)
  }
}

// 角色管理API
export class RoleApiService extends BaseApiService {
  constructor() {
    super('/Role')
  }

  // 角色特定方法
  async getRolePermissions(roleId) {
    return http.get(`/Role/${roleId}/permissions`)
  }

  async assignPermissions(roleId, permissionIds) {
    return http.post(`/Role/${roleId}/permissions`, permissionIds)
  }

  async getRoleUsers(roleId) {
    return http.get(`/Role/${roleId}/users`)
  }

  // 兼容现有API的方法名
  async getAllRoles() {
    return this.getList()
  }

  async getRoleById(id) {
    return this.getById(id)
  }

  async createRole(data) {
    return this.create(data)
  }

  async updateRole(id, data) {
    return this.update(id, data)
  }

  async deleteRole(id) {
    return this.delete(id)
  }
}

// 权限管理API
export class PermissionApiService extends BaseApiService {
  constructor() {
    super('/Permission')
  }

  // 权限特定方法
  async getPermissionTree() {
    return http.get('/Permission/tree')
  }

  async getPermissionsByRole(roleId) {
    return http.get(`/Permission/by-role/${roleId}`)
  }

  // 分配权限给角色
  async assignToRole(roleId, permissionIds) {
    return http.post('/Permission/assign-to-role', {
      RoleId: roleId,
      PermissionIds: permissionIds
    })
  }

  // 清空角色的所有权限
  async clearRolePermissions(roleId) {
    return http.delete(`/Permission/by-role/${roleId}`)
  }

  // 获取所有权限
  async getAllPermissions() {
    return this.getList()
  }

  // 根据ID获取权限
  async getPermissionById(id) {
    return this.getById(id)
  }

  // 创建权限
  async createPermission(data) {
    return this.create(data)
  }

  // 更新权限
  async updatePermission(id, data) {
    return this.update(id, data)
  }

  // 删除权限
  async deletePermission(id) {
    return this.delete(id)
  }

  // 批量更新权限状态
  async batchUpdateStatus(permissionIds, isEnabled) {
    return http.put('/Permission/batch-status', {
      PermissionIds: permissionIds,
      IsEnabled: isEnabled
    })
  }

  // 获取权限统计信息
  async getPermissionStats() {
    return http.get('/Permission/stats')
  }

  // 初始化权限数据
  async initializePermissions() {
    return http.post('/Permission/init')
  }

  // 测试API连接
  async testConnection() {
    return http.get('/Test/db-connection')
  }
}

// 菜单管理API
export class MenuApiService extends BaseApiService {
  constructor() {
    super('/Menu')
  }

  // 菜单特定方法
  async getMenuTree() {
    return http.get('/Menu/tree')
  }

  async getMenuByRole(roleId) {
    return http.get(`/Menu/role/${roleId}`)
  }

  async getMenuPermissions(menuId) {
    return http.get(`/Menu/${menuId}/permissions`)
  }

  // 为角色分配菜单
  async assignMenusToRole(roleId, menuIds) {
    const payload = {
      roleId: roleId,
      menuIds: menuIds
    }
    console.log('MenuApiService.assignMenusToRole 调用:', {
      roleId,
      menuIds,
      payload,
      url: `/Menu/role/${roleId}/assign`
    })
    return http.post(`/Menu/role/${roleId}/assign`, payload)
  }

  // 兼容现有API的方法名
  async getAllMenus() {
    return this.getList()
  }

  async getMenuById(id) {
    return this.getById(id)
  }

  async createMenu(data) {
    return this.create(data)
  }

  async updateMenu(id, data) {
    return this.update(id, data)
  }

  async deleteMenu(id) {
    return this.delete(id)
  }

  async getMenusByRole(roleId) {
    return this.getMenuByRole(roleId)
  }
}

// 操作日志API
export class OperationLogApiService extends BaseApiService {
  constructor() {
    super('/OperationLog')
  }

  // 日志特定方法
  async getLogsByUser(userId, params = {}) {
    return http.get(`/OperationLog/user/${userId}`, { params })
  }

  async getLogsByModule(module, params = {}) {
    return http.get(`/OperationLog/module/${module}`, { params })
  }

  async exportLogs(params = {}) {
    return http.get('/OperationLog/export', { 
      params,
      responseType: 'blob'
    })
  }
}

// 系统配置API
export class SystemConfigApiService extends BaseApiService {
  constructor() {
    super('/SystemConfig')
  }

  // 配置特定方法
  async getConfigByKey(key) {
    return http.get(`/SystemConfig/key/${key}`)
  }

  async updateConfigByKey(key, value) {
    return http.put(`/SystemConfig/key/${key}`, { value })
  }

  async getConfigsByGroup(group) {
    return http.get(`/SystemConfig/group/${group}`)
  }
}

// 个人信息API
export const personalApi = {
  getProfile: (userId) => http.get(`/Personal/${userId}/profile`),
  updateProfile: (userId, data) => http.put(`/Personal/${userId}/profile`, data),
  changePassword: (userId, data) => http.put(`/Personal/${userId}/password`, data)
}

// 文件上传API
export const uploadApi = {
  uploadFile: (formData) => http.post('/upload/file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }),

  uploadImage: (formData) => http.post('/upload/image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }),

  deleteFile: (fileId) => http.delete(`/upload/file/${fileId}`),

  // 上传头像
  avatar: (file) => {
    const form = new FormData()
    form.append('file', file)
    return http.post('/upload/avatar', form, {
      headers: { 'Content-Type': 'multipart/form-data' }
    }).then(res => res.data.url)
  }
}



// 创建服务实例
export const userApi = new UserApiService()
export const roleApi = new RoleApiService()
export const permissionApi = new PermissionApiService()
export const menuApi = new MenuApiService()
export const operationLogApi = new OperationLogApiService()
export const systemConfigApi = new SystemConfigApiService()

// 导出所有API服务
export default {
  auth: authApi,
  user: userApi,
  role: roleApi,
  permission: permissionApi,
  menu: menuApi,
  operationLog: operationLogApi,
  systemConfig: systemConfigApi,
  personal: personalApi,
  upload: uploadApi
} 